﻿// ***********************************************************************
// Assembly         : MVC4Portal
// Author           : LJO+01 (Laurent Jordi)
// Created          : 06-05-2013
// Last Modified By : LJO+01 (Laurent Jordi)
// Last Modified On : 06-05-2013
// ***********************************************************************
// <copyright file="MyProfileController.cs" company="Copyright © Innovacall 2011">
//     Copyright (c) Copyright © Innovacall 2011. All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Transactions;
using System.Web.Mvc;
using System.Web.Security;
using EmitMapper;
using InnovaApp.Layers.DataLayer;
using InnovaApp.Layers.DomainLayer;
using InnovaApp.Layers.ResourcesLayer.Properties;
using InnovaApp.Portals.MVC4Portal.Models.MetaModels.ContactManagement;
using InnovaApp.Portals.MVC4Portal.Models.ViewModels.LayoutViewModels;
using INNOVACALL.Framework.Common;
using INNOVACALL.Framework.Common.MVCHelpers;

namespace InnovaApp.Portals.MVC4Portal.Controllers.ViewControllers.LayoutViewControllers
{
    /// <summary>
    /// Class MyProfileController
    /// </summary>
    public class MyProfileController : _LayoutViewControllers_Base<MyProfile_ViewModel>
    {
        /// <summary>
        /// Initializes data that might not be available when the constructor is called.
        /// </summary>
        /// <param name="requestContext">The HTTP context and route data.</param>
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.eMethodBase = "InnovaApp.Portals.InnovaAppFrontOfficePortal.Controllers.MyProfileController";
            base.specificCssCollection = new string[] { "Views/MyProfile.css", "ClientComponents/CodeFormatting/csharp.css", "ClientComponents/KendoUI/kendo.common.min.css", "ClientComponents/KendoUI/kendo." + ConfigurationManager.AppSettings["KendoUITheme"] + ".min.css" };
            base.specificJSCollection = null;
            base.dynamicJSCollection = new string[] { "/ScriptsG/MyProfileDynamic.js" };
            base.specificJqueryJSCollection = new string[] { "ClientComponents/KendoUI/kendo.web.min.js", "InnovacallJS/MyProfile/MyProfile.js" };
            base.externalCss = null;
            base.Meta.Add(enMeta.Description, string.Empty);
            base.Meta.Add(enMeta.Keywords, string.Empty);
            base.Meta.Add(enMeta.Subject, string.Empty);

            base.Initialize(requestContext);
        }

        /// <summary>
        /// Indexes this instance.
        /// </summary>
        /// <returns>ActionResult.</returns>
        [HttpGet, Authorize, CacheManager(enCacheMode.NoCache)] 
        public ActionResult Index(string language)
        {
            base.LocalizeDynamicScript(language);
            //ViewBag.Message = "Modify this template to kick-start your ASP.NET MVC application.";
            using (DataRepositories _dataContext = new DataRepositories())
            {
                base.InitView(
                    pageTitle: Resources.View_MyProfile_PageTitle,
                    openingMessage: Resources.View_MyProfile_PageMessage,
                    specificCssCollection: specificCssCollection,
                    specificJSCollection: specificJSCollection,
                    dynamicJSCollection: dynamicJSCollection,
                    specificJqueryJSCollection: specificJqueryJSCollection,
                    jsVariables: jsVariables,
                    externalJs: externalJs,
                    externalCss: externalCss,
                    metaToAdd: Meta,
                    _dataContext: _dataContext,
                    displayMenus: true,
                    language: base.RequestLanguage,
                    adminMode: false,
                    usesKendoUI: true,
                    jQueryUITheme: InnovaApp.Layers.CommonLayer.Controllers.Environment.JQueryUITheme,
                    kendoUITheme: InnovaApp.Layers.CommonLayer.Controllers.Environment.KendoUITheme,
                    currentUser: Membership.GetUser()
                    );

                if (Request.QueryString["ReturnUrl"] != null)
                {
                    ContentData.ReturnUrlMessage = Resources.View_MyProfile_PageMessage_Redirected;
                }

                MembershipUser CurrentUser = Membership.GetUser();

                Contact dbContact = _dataContext.Contact_Rep.Query(x => x.FK_InnoAppUser == (Guid)CurrentUser.ProviderUserKey).FirstOrDefault();

                if (dbContact == null)
                {
                    ContentData.Contact = new Models.MetaModels.ContactManagement.Contact_MetaModel();
                }
                else
                {
                    ContentData.Contact = ObjectMapperManager.DefaultInstance.GetMapper<Contact, Contact_MetaModel>().Map(dbContact);
                }

                List<SelectListItem> Genres = _dataContext.Genre_Rep.GetAll().OrderBy(x => x.SortIndex).Select(x => new SelectListItem() { Value = x.Id.ToString(), Text = x.Name, Selected = (x.Id == ContentData.Contact.FK_Genre) }).ToList();
                Genres.Insert(0, new SelectListItem() { Value = "-1", Text = string.Empty, Selected = (dbContact == null) });
                ContentData.Contact.Genres = Genres;
            }
            return View(ContentData);
        }

        /// <summary>
        /// Indexes the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns>JsonResult.</returns>
        [HttpPost, Authorize, CacheManager(enCacheMode.NoCache)]
        public JsonResult Index(MyProfile_ViewModel model)
        {
            string eMethod = eMethodBase + "Index[Post]";
            string returnToUrl = Request.QueryString["ReturnUrl"];
            string scriptToExecute = string.Empty;
            object eParameters = new { @modelContactId = model.Contact.Id, @modelContactFK_Genre = model.Contact.FK_Genre, @modelContactFirstName = model.Contact.FirstName, @modelContactLastName = model.Contact.LastName };
            JsonResult toReturn = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };

            using (TransactionScope TS = new TransactionScope())
            {
                try
                {
                    using (DataRepositories _dataContext = new DataRepositories())
                    {
                        Guid currentUserId = (Guid)Membership.GetUser().ProviderUserKey;
                        Contact dbContact = _dataContext.Contact_Rep.Query(x => x.FK_InnoAppUser == currentUserId).FirstOrDefault();
                        if (dbContact == null)
                        {
                            dbContact = new Contact();
                            dbContact.FK_InnoAppUser = currentUserId;
                        }
                        dbContact.FK_Genre = model.Contact.FK_Genre;
                        dbContact.FirstName = model.Contact.FirstName;
                        dbContact.LastName = model.Contact.LastName;
                        _dataContext.Contact_Rep.AddUpdate(dbContact);
                        _dataContext.Save();
                        TS.Complete();
                    }
                    if (!string.IsNullOrEmpty(returnToUrl))
                    {
                        scriptToExecute = "$.fn.NavigateTo('" + returnToUrl + "')";
                    }
                    toReturn.Data = new { @success = true, @scriptToExecute = scriptToExecute, @divToUpdate = string.Empty };
                    return toReturn;
                }
                catch (Exception ex)
                {
                    TS.Dispose();
                    throw ex;
                }
            }
        }
    }
}
